package net.yb.servlet;

import com.alibaba.fastjson.JSON;
import net.yb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");

        /**
         * 响应网页
         */
        // resp.setContentType("text/html; charset=utf8");
        // PrintWriter out = resp.getWriter();
        // out.print("<h1 style='color:red;'>欢迎您：" + name + "</h1>");
        // out.close();

        /**
         * 响应JSON数据
         */
        resp.setContentType("application/json; charset=utf8");
        PrintWriter out = resp.getWriter();

        User user = new User(1, name, "123", 18, "男", 180.7, new Date());
        // 使用fastjson，将user对象转为JSON字符串
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);

        out.print(jsonString);
        out.close();
    }
}
